package com.haitonghop.requester;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.haitonghop.data.GreatAppItem;
import com.haitonghop.network.Request;
import com.haitonghop.network.RequestListener;

public class GreatAppRequester extends Request{

	RequestListener listener = null;
	public GreatAppRequester(RequestListener listener){
		this.listener = listener;
	}

	ArrayList<GreatAppItem> appItems = new ArrayList<GreatAppItem>();
	public ArrayList<GreatAppItem> getData(){
		return this.appItems;
	}
	@Override
	public void cancelRequest() {
		// TODO Auto-generated method stub

	}

	@Override
	public void runRequest() {
		// TODO Auto-generated method stub
		url = "http://haibl.net/public/apps?key=2861010";
		send();
	}

	@Override
	public void requestFinished(JSONObject jsonObject) {
		// TODO Auto-generated method stub
		if(jsonObject != null){
			try {
				JSONArray data = jsonObject.has("data") ? jsonObject.getJSONArray("data") : null;
				if(data != null){
					for(int i = 0 , n = data.length() ; i < n ; i++){
						JSONObject child = data.getJSONObject(i);
						String appName = child.has("appName") ? child.getString("appName") : "";
						int status = child.has("status") ? child.getInt("status") : -1;
						String avatar = child.has("avatar") ? child.getString("avatar") : "";
						String link = child.has("link") ? child.getString("link") : "";
						String desc = child.has("desc") ? child.getString("desc") : "";

						GreatAppItem appItem = new GreatAppItem();
						appItem.appName = appName;
						appItem.avatar = avatar;
						appItem.des = desc;
						appItem.link = link;
						appItem.status = status;

						appItems.add(appItem);
					}
				}

				if(listener != null){
					listener.onRequestComplete(this);
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	@Override
	public void requestFailed(int errorCode, String message) {
		// TODO Auto-generated method stub
		if(listener != null){
			listener.onRequestFailed(message, this);
		}
	}

}
